﻿<%@ WebHandler Language="C#" Class="UpLoadFile" %>

using System;
using System.Web;
using System.IO;
using System.Net;
using System.Data;
using ebay.Utility;
using System.Text.RegularExpressions;

public class UpLoadFile : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        string type = context.Request["type"];
        HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
        HttpPostedFile file = files["fup"];
        if (string.IsNullOrEmpty(type))
        {
            context.Response.Write("上传文件类型不正确");
            return;
        }
        type = WebUtility.InputText(type, 20);

        string retCode = "1";
        string retMsg = "Failure";

        switch (type)
        {
            case "excel":
                {
                    string tableName = context.Request["tid"];
                    if (string.IsNullOrEmpty(tableName))
                    {
                        context.Response.Write("1参数错误!");
                        return;
                    }
                    if (!IsValidFileType(file.FileName, type)) //验证文件类型
                    {
                        retCode = "1";
                        retMsg = "上传文件类型不正确";
                    }
                    string filepath = context.Server.MapPath("~") + "\\UpLoad\\";
                    if (!Directory.Exists(filepath))
                    {
                        Directory.CreateDirectory(filepath);
                    }
                    string oldFileName = file.FileName;
                    string name = Guid.NewGuid().ToString() + GetExtension(file.FileName);
                    string strNewPath = filepath + name;
                    try
                    {
                        file.SaveAs(strNewPath);
                    }
                    catch (Exception ex)
                    {
                        Log.WriteLog(ex.ToString());
                        retCode = "1";
                        retMsg = "文件保存失败";
                    }
                    switch (tableName.ToLower())
                    {
                        case "43"://红字销售出库单
                            Match XS_Name = Regex.Match(oldFileName, ".*[.]csv$");
                            if (XS_Name.Success)
                            {
                                bool val = false;
                                int iCount = 0;
                                SyncExcel sync = new SyncExcel();
                                try
                                {
                                    val = sync.WriteToK3XOUT(strNewPath, ref iCount);

                                    if (val)
                                    {
                                        retCode = "0";
                                        retMsg = "成功导入";
                                    }
                                    else
                                    {
                                        retCode = "1";
                                        retMsg = "导入失败";
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Log.WriteLog(ex.ToString());
                                    retCode = "1";
                                    retMsg = ex.Message;
                                }
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "只支持.csv格式!";
                            }
                            break;
                        case "42"://PPOrder 
                            Match m_Name = Regex.Match(oldFileName, ".*[.]csv$");
                            if (m_Name.Success)
                            {
                                bool val = false;
                                int iCount = 0;
                                SyncExcel sync = new SyncExcel();
                                try
                                {
                                    val = sync.WriteToServer(strNewPath, ref iCount);

                                    if (val)
                                    {
                                        retCode = "0";
                                        retMsg = "成功导入：" + iCount + "条";

                                    }
                                    else
                                    {
                                        retCode = "1";
                                        retMsg = "导入失败";
                                    }
                                }
                                 catch (Exception ex)
                                {
                                    Log.WriteLog(ex.ToString());
                                    retCode = "1";
                                    retMsg = ex.Message;
                                }
                            }
                            else
                            {
                                retCode = "1";
                                retMsg = "只支持.csv格式!";
                            }
                            break;
                        case "41"://ebaySelling
                            {
                                int bIndex = oldFileName.IndexOf("[");
                                int eIndex = oldFileName.IndexOf("]");
                                if (bIndex != -1 && eIndex != -1)
                                {
                                    string ebayUserId = oldFileName.Substring(bIndex + 1, eIndex - bIndex - 1);
                                    bool val = false;
                                    SyncExcel sync = new SyncExcel();
                                    System.Collections.Generic.List<ebay.Model.EbaySelling> ebaySellingList = new System.Collections.Generic.List<ebay.Model.EbaySelling>();
                                    bool getSuccess = true;
                                    try
                                    {
                                        ebaySellingList = sync.GetEbaySelling(strNewPath, ebayUserId);//读取excel格式的ebaySelling数据。
                                    }
                                    catch (Exception ex)
                                    {
                                        retCode = "1";
                                        retMsg = ex.Message;
                                        getSuccess = false;
                                    }
                                    finally
                                    {
                                        File.Delete(strNewPath);
                                    }
                                    if (getSuccess)
                                    {
                                        ebay.Dal.EbaySelling ebaySelling = new ebay.Dal.EbaySelling();
                                        val = ebaySelling.Add(ebayUserId, ebaySellingList);//写数据
                                        if (val)
                                        {
                                            retCode = "0";

                                            retMsg = "导入成功!";
                                        }
                                        else
                                        {
                                            retCode = "1";

                                            retMsg = "导入失败!";
                                        }
                                    }
                                }
                                else
                                {
                                    retCode = "1";
                                    retMsg = "文件名应为[EbayAccount]格式!";
                                }
                            }
                            break;
                    }
                    try
                    {
                        File.Delete(strNewPath);
                    }
                    catch
                    {

                    }
                }
                break;                        
            case "img":
                {
                    string act = context.Request["act"];
                    if (!string.IsNullOrEmpty(act))
                    {
                        act = WebUtility.InputText(act, 10);
                        switch (act)
                        {
                            case "up":
                                {
                                    if (!IsValidFileType(file.FileName, type)) //验证文件类型
                                    {
                                        retCode = "1";
                                        retMsg = "上传文件类型不正确";
                                    }
                                    string picPath = context.Server.MapPath("~") + "\\UpLoad\\Product\\";
                                    if (!Directory.Exists(picPath))
                                    {
                                        Directory.CreateDirectory(picPath);
                                    }
                                    string name = Guid.NewGuid().ToString() + GetExtension(file.FileName);
                                    string strNewPath = picPath + name;
                                    try
                                    {
                                        file.SaveAs(strNewPath);
                                    }
                                    catch(Exception ex)
                                    {
                                        Log.WriteLog(ex.ToString());
                                        retCode = "1";
                                        retMsg = "文件保存失败";
                                    }
                                    retCode = "0";
                                    retMsg = name;
                                }
                                break;
                            case "del":
                                {
                                    string picName = context.Request["picname"];

                                    string picPath = context.Server.MapPath("~") + "\\UpLoad\\Product\\" + picName;
                                    if (File.Exists(picPath))
                                    {
                                        try
                                        {
                                            File.Delete(picPath);
                                            retCode = "0";
                                        }
                                        catch(Exception ex)
                                        {
                                            Log.WriteLog(ex.ToString());
                                            retCode = "0";
                                            retMsg = "删除失败!";

                                        }
                                    }
                                    else
                                    {
                                        retCode = "0";
                                    }

                                }
                                break;
                        }
                    }
                    break;
                }
        }
        context.Response.Write("[{\"retCode\":\"" + retCode + "\",\"retMsg\":\"" + retMsg + "\"}]");
    }

    bool IsDBNull(object o)
    {
        return o == DBNull.Value;
    }

    /// <summary>
    /// 验证文件类型
    /// </summary>
    /// <param name="FileName"></param>
    /// <returns></returns>
    private bool IsValidFileType(string FileName, string typeName)
    {
        string[] _AcceptedFileTypes = null;
        if (typeName == "excel")
        {
            _AcceptedFileTypes = new string[] { "xls","csv" };
        }
        else if (typeName == "img")
        {
            _AcceptedFileTypes = new string[] { "jpg", "jpeg", "bmp", "png" };
        }
        string ext = FileName.Substring(FileName.LastIndexOf(".") + 1, FileName.Length - FileName.LastIndexOf(".") - 1);
        for (int i = 0; i < _AcceptedFileTypes.Length; i++)
        {
            if (ext == _AcceptedFileTypes[i])
            {
                return true;
            }
        }
        return false;
    }

    /// <summary>
    /// 获得文件扩展名
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    private string GetExtension(string fileName)
    {
        try
        {
            int startPos = fileName.LastIndexOf(".");
            string ext = fileName.Substring(startPos, fileName.Length - startPos);
            return ext;
        }
        catch
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// 创建文件要保存的路径
    /// </summary>
    /// <param name="picPath">文件路径</param>
    /// <returns></returns>
    private string GetSaveFilePath(string picPath)
    {
        if (!Directory.Exists(picPath))
        {
            Directory.CreateDirectory(picPath);
        }
        return picPath;
    }
    
    public bool IsReusable {
        get {
            return false;
        }
    }

}